﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using JLL.China.Application;
using JLL.China.Infrastructure.Services;
using JLL.China.Web.Areas.Portal.Models;
using JLL.China.Web.Libraries;
using Image = System.Drawing.Image;

namespace JLL.China.Web.Areas.Portal.Controllers
{
    public class HomeBannerController : Controller
    {
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);
        // GET: /Portal/HomeBanner/
        public HomeBannerController()
        {
            ViewData["now_controller"] = "Portal/HomeBanner/";
            ViewData["TitleEvent"] = "Home Banner";
        }
        //public ActionResult Index(int? page)
        //{

        //    if (Session["page_size_default"] != null)
        //    {
        //        ViewData["per-page"] = Session["page_size_default"].ToString();
        //        defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
        //    }
        //    else
        //    {
        //        ViewData["per-page"] = defaultPageSize;
        //    }
        //    int currentPageIndex = page.HasValue ? page.Value : 1;
        //    //Strore Session
        //    Session["pageindex"] = currentPageIndex;
        //    var model = BannerService.FindByGroupFid(1).ToPagedList(currentPageIndex, defaultPageSize);
        //    //            ViewData["bannercount"] = model.Count;
        //    //            Session["bannercount"] = model.Count;
        //    // return View("../Content/Index", model);
        //    return View(model);
        //}

        
        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        [Authorize]
        public ActionResult Create(decimal? id)
        {
            //            ViewData["bannercount"] = Session["bannercount"];
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            if (id != null)
            { //for edit
                BannerModel model = new BannerModel();
                model.Banner = BannerService.FindByID_LanguageFid(id, 1);
                model.Banner_Local = BannerService.FindByID_LanguageFid(id, 2);
                return View(model);

            }
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(BannerModel model, HttpPostedFileBase file)
        {
            //            ViewData["bannercount"] = Session["bannercount"];
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = 0;//insert/update unsuccessfully
            model.Banner.BannerUrl = UploadFile(file);
            model.Banner.BannerGroupFID = 1;//home banner
            model.Banner.Type = "dynamic";
            if (model.Banner.Banner_ID == null) //for insert
            {
                res = BannerService.CreateBanner(model.Banner, model.Banner_Local);

            }
            else //for update
            {
                res = BannerService.UpdateBanner(model.Banner, model.Banner_Local);
            }
            if (res != -1)
            {

                ShowMessage("Saved successfully.", "Success");
            }
            else
            {
                ShowMessage("Saved unsuccessfully.", "Error");
            }

            return RedirectToAction("Index");

        }

        private string UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file == null)
                {
                    return null;
                }

                string mediaRootPath = Server.MapPath("~/Media/Banner/Home");


                if (!Directory.Exists(mediaRootPath))
                {
                    Directory.CreateDirectory(mediaRootPath);
                }
                string name = System.IO.Path.GetFileName(file.FileName);
                string fullFilePath = mediaRootPath + "\\" + name;

                ResizeStream(new Size(356,283), file.InputStream, fullFilePath);

                //file.SaveAs(fullFilePath);

                return name;

            }
            catch (Exception)
            {

                return null;
            }

        }

        public void ResizeStream(Size imageSize, Stream filePath, string outputPath)
        {
            var image = Image.FromStream(filePath);

            int newWidth, newHeight;


            newWidth = imageSize.Width;
            newHeight = imageSize.Height;


            var thumbnailBitmap = new Bitmap(newWidth, newHeight);

            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbnailGraph.DrawImage(image, imageRectangle);

            thumbnailBitmap.Save(outputPath, image.RawFormat);
            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
            image.Dispose();
        }

        public ActionResult ChangeStatus(decimal id, bool status)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }

            //var model = BannerService.FindByID_LanguageFid(id, 1);
            //var model_local = BannerService.FindByID_LanguageFid(id, 2);


            //model.Status = !model.Status ;

            //BannerService.UpdateBanner(model, model_local);
            BannerService.ChangeStatus(id.ToString(), !status);
            ShowMessage("Records updated successfully.", "Success");
            return RedirectToAction("Index", new { page = Session["pageindex"] });
        }


        public ActionResult BulkProcess(string status, IEnumerable<decimal> selected)
        {
            try
            {
                if (!checkUserLogin())
                {
                    return RedirectToAction("LogIn", "Home", new { area = "" });
                }
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                if (status.Equals("active"))
                {
                    //   NewsService.ChangeEventStatus(arr_id, true);
                    BannerService.ChangeStatus(arr_id, true);
                }

                if (status.Equals("inactive"))
                {
                    //EventService.ChangeEventStatus(arr_id, false);
                    BannerService.ChangeStatus(arr_id, false);
                }

                if (status.Equals("remove"))
                {
                    BannerService.RemoveSelected(arr_id);
                }
                ShowMessage("Records updated successfully.", "Success");
            }
            catch (Exception)
            {
                ShowMessage("Records updated unsuccessfully.", "Error");
            }


           // return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
              return RedirectToAction("Index");
        }

        public ActionResult Delete(decimal? id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = 0;
            if (id != null)
                res = BannerService.DeleteBanner(id);
            if (res != -1)
            {
                /*Session["message"] = "Records updated successfully.";
                Session["messageType"] = "Success";*/
                ShowMessage("Records deleted successfully.", "Success");
            }
            else
            {
                /*Session["message"] = "Records updated unsuccessfully.";
                Session["messageType"] = "Error";*/
                ShowMessage("Records deleted unsuccessfully.", "Error");

            }
            //return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
            return RedirectToAction("Index");
        }

        void ShowMessage(string msg, string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }

        public string SaveOrder(string id)
        {
          
            string[] arrData = id.Split(',');
            int countnum = arrData.Length;
            for (int i = 0; i < countnum;i++ )
            {
               // UpdateOrder(arrData[i],i+1,1);
               // UpdateOrder(arrData[i], i + 1, 2);

            }
            for (int i = 0; i < arrData.Length; i++)
            {
                BannerService.UpdateOrder(decimal.Parse(arrData[i]),i+1);
            }
            return "OK";
        }

        [Authorize]
        public ActionResult Index(decimal? id)
        {
            //            ViewData["bannercount"] = Session["bannercount"];
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            BannerModel model = new BannerModel();
            model.Banners = BannerService.FindByGroupFid(1);

            if (id != null)
            { //for edit
                model.Banner = BannerService.FindByID_LanguageFid(id, 1);
                model.Banner_Local = BannerService.FindByID_LanguageFid(id, 2);
            }
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(BannerModel model, HttpPostedFileBase file)
        {
            //            ViewData["bannercount"] = Session["bannercount"];
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = 0;//insert/update unsuccessfully
            model.Banner.BannerUrl = UploadFile(file);
            model.Banner.BannerGroupFID = 1;//home banner
            model.Banner.Type = "dynamic";
            if (model.Banner.Banner_ID == null) //for insert
            {
                res = BannerService.CreateBanner(model.Banner, model.Banner_Local);

            }
            else //for update
            {
                res = BannerService.UpdateBanner(model.Banner, model.Banner_Local);
            }
            if (res != -1)
            {

                ShowMessage("Records created successfully.", "Success");
            }
            else
            {
                ShowMessage("Records updated unsuccessfully.", "Error");
            }

            return RedirectToAction("Index");

        }


    }
}
